import NP from 'number-precision'
export function getLevelById(treeList, id, level = 1) {
  if (!(treeList instanceof Array)) {
    return 0
  }
  if (treeList.length === 0) {
    return 0
  }
  const found = treeList.find((node) => {
    if (node.id === id) {
      return true
    }
    const ret = getLevelById(node.children, id, level + 1)
    if (ret === 0) {
      return false
    } else {
      level = ret
      return true
    }
  })

  if (found) {
    return level
  } else {
    return 0
  }
}

/**
 * @param treeList
 * @param strictly : boolean,是否只获取子节点的key，默认false
 * @returns {Array}
 */
export function getKeysFromTree(treeList, strictly = false) {
  if (!treeList || !(treeList instanceof Array) || treeList.length === 0) {
    return []
  }
  let keyArray = []
  treeList.forEach((node) => {
    if (!node.children || node.children.length === 0 || !strictly) {
      keyArray.push(node.id)
    }
    keyArray = [...keyArray, ...getKeysFromTree(node.children, strictly)]
  })

  return keyArray
}

/**
 * 创建一个新tree, 其包含通过所提供函数实现的测试的所有元素。若父节点测试不通过继续测试children
 * @param treeList
 * @param cb 过滤函数,返回Boolean值
 * @returns {Array}
 */
export function filterTree(treeList, cb) {
  const newList = []
  if (treeList) {
    treeList.map(node => {
      const children = filterTree(node.children, cb)
      if (cb(node) || children.length > 0) {
        const newNode = Object.assign({}, node)
        if (children.length > 0) {
          newNode.children = children
        } else {
          delete newNode.children
        }
        newList.push(newNode)
      }
    })
  }
  return newList
}
/**
 * 创建一个新tree, 其包含通过所提供函数实现的测试的所有元素。若父节点测试不通过则不考虑children
 * @param treeList
 * @param callback : function 参数 node
 * @returns {Array}
 */
export function filterTreeByParent(treeList, callback) {
  const nodes = []
  if (treeList) {
    treeList.forEach(node => {
      if (callback(node)) {
        const newNode = Object.assign({}, node)
        const children = filterTreeByParent(node.children, callback)
        if (children.length > 0) {
          newNode.children = children
        } else {
          delete newNode.children
        }
        nodes.push(newNode)
      }
    })
  }
  return nodes
}
/**
 * 创建一个新tree，其结果是该tree中的每个元素都调用一次提供的函数后的返回值。
 * @param treeList
 * @param callback : function 参数 node
 * @returns {Array}
 */
export function mapTree(treeList, callback) {
  if (!treeList || !(treeList instanceof Array) || treeList.length === 0) {
    return []
  }
  const nodes = []
  treeList.forEach((node) => {
    let children
    if (node.children && node.children.length !== 0) {
      children = mapTree(node.children, callback)
    }
    const newNode = callback(node)
    newNode.children = children
    nodes.push(newNode)
  })

  return nodes
}
/**
 * 将树treeList转成一维数组
 * @param treeList
 * @param strictly: boolean,是否只获取子节点，默认true
 * @returns {Array}
 */
export function getArrayFromTree(treeList, strictly = true) {
  if (!treeList || !(treeList instanceof Array) || treeList.length === 0) {
    return []
  }
  let nodes = []
  treeList.forEach((node) => {
    if (!node.children || node.children.length === 0 || !strictly) {
      nodes.push(node)
    }
    nodes = [...nodes, ...getArrayFromTree(node.children, strictly)]
  })

  return nodes
}
/**
 * 给tree的每一个节点添加属性key,值为value
 * @param treeList
 * @param key
 * @param value
 */
export function setAttrForTree(treeList, key, value) {
  if (!treeList || !(treeList instanceof Array) || treeList.length === 0) {
    return
  }
  treeList.forEach((node) => {
    node[key] = value
    setAttrForTree(node.children, key, value)
  })
}

export function getNameById(treeList, id, prop) {
  let { idProp, nameProp } = { idProp: 'id', nameProp: 'name' }
  if (prop) {
    idProp = prop.id
    nameProp = prop.name
  }
  let name
  if (!treeList || !(treeList instanceof Array) || treeList.length === 0) {
    return name
  }
  treeList.find((node) => {
    if (node[idProp] === id) {
      name = node[nameProp]
      return true
    }
    name = getNameById(node.children, id, prop)
    if (name === undefined) {
      return false
    } else {
      return true
    }
  })
  return name
}

/**
 * 获取纯根节点列表
 * @param treeList
 * @param prop
 * @returns {*}
 */
export function getRootList(treeList, prop) {
  if (!treeList || !(treeList instanceof Array) || treeList.length === 0) {
    return []
  }
  let { idProp, nameProp } = { idProp: 'id', nameProp: 'name' }
  if (prop) {
    idProp = prop.id
    nameProp = prop.name
  }
  return treeList.map((item) => {
    return {
      [idProp]: item[idProp],
      [nameProp]: item[nameProp]
    }
  })
}

export function getChildrenById(treeList, id) {
  let children
  if (!treeList || !(treeList instanceof Array) || treeList.length === 0) {
    return children
  }
  treeList.find((node) => {
    if (node.id === id) {
      children = node.children
      return true
    }
    children = getChildrenById(node.children, id)
    if (children === undefined) {
      return false
    } else {
      return true
    }
  })
  return children
}

// Get Erp Constant
export function getConstantByType(constants, type) {
  const tmp = constants.filter(constant => constant.type === type)
  if (tmp && tmp.length > 0) {
    return tmp[0].data
  }
  return []
}

// deal with aside css
export function getIconClass(node) {
  if (node.isLeaf) {
    return 'documentation2'
  } else {
    // 之前照片变为documentation1，folder-opened1
    // return node.expanded ? 'folder-opened' : 'folder'
    return 'folder-opened2'
  }
}
export function getIconClassName(node) {
  if (node.isLeaf) {
    return 'tree-leaf'
  } else {
    return ''
  }
}

// 分组统计
/**
 *分组归类属性
 * @param array
 * @param attr 要分组的属性
 * @returns {*[]}
 */
export function groupBy(array, attr) {
  const groups = {}
  array.forEach(function(o) {
    const group = o[attr]
    groups[group] = groups[group] || []
    groups[group].push(o)
  })
  return Object.keys(groups).map(function(group) {
    return groups[group]
  })
}

/**
 * 分组统计属性总和
 * @param array
 * @param attr 分组的属性
 * @param valueAttr 分组的属性要统计的属性
 * @returns {{}[]}
 */
export function groupCount(array, attr, valueAttr) {
  const groups = {}
  array.forEach(function(o) {
    const group = o[attr]
    groups[group] = groups[group] || 0
    groups[group] = NP.plus(groups[group], parseFloat(o[valueAttr]))
  })
  return Object.keys(groups).map(function(group) {
    return {
      [attr]: group,
      [valueAttr]: NP.round(groups[group], 4)
    }
  })
}

/**
 * 从一组整数中分离出连续的整数集
 * @param indexArray 一组整数
 * @returns {Array}
 */
export function groupSeries(indexArray) {
  const groupArray = []
  let pre = indexArray[0]
  let group = []
  groupArray.push(group)
  group.push(pre)
  for (let i = 1; i < indexArray.length; i++) {
    if (indexArray[i] === pre + 1) {
      group.push(++pre)
    } else {
      pre = indexArray[i]
      group = []
      groupArray.push(group)
      group.push(pre)
    }
  }
  return groupArray
}

/**
 * 上移、下移数组元素,会改变原有数组
 * @param array
 * @param indexArray
 * @param direction
 */
export function move(array, indexArray, direction) {
  if (array.length === 0 || indexArray.length === 0 || direction === 0) return

  // 将要移动的元素组装成连续的分组
  indexArray = indexArray.sort((a, b) => a - b)
  const groupIndexArray = groupSeries(indexArray)
  const groupArray = []
  groupIndexArray.forEach(grroupIndex => {
    const group = grroupIndex.map(index => array[index])
    groupArray.push(group)
  })
  // 开始移动
  if (direction > 0) { // 上移
    groupArray.forEach(group => {
      const index = group[0].index
      if (direction > 0 && index === 0) return
      array[index - 1 + group.length] = array.splice(index - 1, group.length, ...group)[0]
    })
  } else { // 下移
    groupArray.reverse().forEach(group => {
      const beginIndex = group[0].index
      const endIndex = group[group.length - 1].index
      if (direction < 0 && endIndex === array.length - 1) return
      array[beginIndex] = array.splice(beginIndex + 1, group.length, ...group)[group.length - 1]
    })
  }
}

/**
 * 数据导出csv格式
 * @param title//导出文件名
 * @param headers//多级表头数据
 * @param column//显示字段prop和表头name
 * @param data//导出数据
 */
export function exportData(headers, title, columns, data, merges) {
  import('@/vendor/Export2Excel').then(excel => {
    const multiHeader = [headers] // 前两行的表头数据，二维数组，不够的用空白补全
    const header = [] // 最后一行的表头数据
    columns.map(column => {
      header.push(column.name)
    })

    function formatData(data, columns) {
      return data.map(item => columns.map(column => item[column.prop]))
    }
    const exportData = formatData(data, columns)
    if (headers.length > 0 && merges.length > 0) {
      excel.export_json_to_excel({
        multiHeader,
        merges,
        header,
        data: exportData,
        filename: title,
        autoWidth: true,
        bookType: 'xlsx'
      })
    } else {
      excel.export_json_to_excel({
        header,
        data: exportData,
        filename: title,
        autoWidth: true,
        bookType: 'xlsx'
      })
    }
  })
}

/**
 * 将element导出pdf文件
 * @param title
 * @param element
 */
export function exportPdf(title, element, option) {
  import('@/vendor/Export2Pdf').then(jsPDF => {
    jsPDF.save(title, element, option)
  })
}

/**
 * 统计多个需要的值   纸板排程(新)--示例
 * @param array
 * @param attr 分组的属性
 * @param valueAttr 分组的属性要统计的属性 ---总和
 * @param otherAttr 分组的属性要统计的属性 ---总和
 * @param Third 分组的第三个属性
 * @param Fourth 分组的第四个属性
 * @returns {{}[]}
 */
export function multipleGroupCount(array, attr, valueAttr, otherAttr, Third, Fourth) {
  const groups = {}
  array.forEach(function(o) {
    const group = o[attr]
    groups[group] = groups[group] || 0
    if (groups[group] === 0) {
      groups[group] = [NP.plus(groups[group], parseFloat(o[valueAttr])), NP.plus(groups[group], parseFloat(o[otherAttr])), o[Third], o[Fourth]]
    } else {
      groups[group] = [NP.plus(groups[group][0], parseFloat(o[valueAttr])), NP.plus(groups[group][1], parseFloat(o[otherAttr])), o[Third], o[Fourth]]
    }
  })
  return Object.keys(groups).map(function(group) {
    return {
      [attr]: group,
      [valueAttr]: NP.round(groups[group][0], 4),
      [otherAttr]: groups[group][1],
      [Third]: groups[group][2],
      [Fourth]: groups[group][3]
    }
  })
}

/**
 * 自定义表格排序
 * @param arr 数组
 * @param cabinet 排序的规则
 * @param type 数组item对应规则的字段
 */
export function customArrSort(arr, cabinet, type) {
  arr.sort((a, b) => {
    return cabinet.indexOf(a[type.replace("'", '')]) - cabinet.indexOf(b[type.replace("'", '')])
  })
  const result = arr.map((item) => {
    return item
  })
  return result
}
